package com.cqc.manage.controller;

import cn.hutool.core.date.DateUtil;
import com.cqc.manage.dto.EquRecordDto;
import com.cqc.manage.dto.JsonResultDto;
import com.cqc.manage.entity.Equipment;
import com.cqc.manage.service.Imp.equipmentService.EquMessageService;

import com.cqc.manage.util.FileUtils;
import com.cqc.manage.util.excel.EquRecordDataListener;
import com.cqc.manage.util.excel.EquRecordData;
import com.cqc.manage.util.excel.ExcelUtil;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//上传不要用@Controller,用@RestController
@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    //在文件操作中，不用/或者\最好，推荐使用File.separator
    private final static String fileDir="files";
    private final static String property = System.getProperty("user.dir");   // 获取项目更目录
    private final static String rootPath = System.getProperty("user.home")+ File.separator+fileDir+File.separator;

    @Autowired
    private EquMessageService equMessageService;

    @Autowired
    private EquRecordDataListener equRecordDataListener;

    /**
     * 下载文件 收费通知
     * @param res
     * @param filename
     * @return
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public JsonResultDto downloadData(HttpServletResponse res, @RequestParam("filename")String filename) {
//        String data="E:\\code\\pycharm\\cqc-python\\pdf\\"+filename;   //传入数据
        String data = "/root/cqc/pdf/"+filename+"/"+filename;
        File file=new File(data);
//        FileUtils.getFile(data.getBytes(),file.getName());
        FileUtils.responseTo(file,res);
//        file.delete();
        System.out.println("success");
        return new JsonResultDto("200","success");
    }


    /**
     * 下载文件 收费通知
     * @param res
     * @param filename
     * @return
     */
    @RequestMapping(value = "/reportDownload", method = RequestMethod.GET)
    public JsonResultDto downloadReport(HttpServletResponse res, @RequestParam("filename")String filename) {
//        String data="E:\\code\\pycharm\\cqc-python\\pdf\\"+filename;   //传入数据
        String data = "/root/cqc-java/report/"+filename;
//        String data = "E:\\code\\backEnd\\springboot-websocket\\report\\"+filename;
        File file=new File(data);
        FileUtils.responseTo(file,res);
        System.out.println("success");
        return new JsonResultDto("200","success");
    }



//    @RequestMapping(value = "/uploadEquRecord" , method = RequestMethod.POST)
    public Object uploadFile(@RequestParam("file") MultipartFile[] multipartFiles, final HttpServletResponse response, final HttpServletRequest request){
        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        try {
            if (multipartFiles != null && multipartFiles.length > 0) {
                for(int i = 0;i<multipartFiles.length;i++){
                    try {
                        //以原来的名称命名,覆盖掉旧的
                        String storagePath = rootPath+multipartFiles[i].getOriginalFilename();
                        logger.info("上传的文件：" + multipartFiles[i].getName() + "," + multipartFiles[i].getContentType() + "," + multipartFiles[i].getOriginalFilename()
                                +"，保存的路径为：" + storagePath);
                        Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
                        //或者下面的
                        // Path path = Paths.get(storagePath);
                        //Files.write(path,multipartFiles[i].getBytes());
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                    }
                }
            }

        } catch (Exception e) {
            return new JsonResultDto("201","上传失败");
        }
        return new JsonResultDto("200","上传成功");
    }



    /**
     * 上传设备使用记录
     * @param file
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * String
     */
//    @PostMapping("/uploadEquRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    //@RequestMapping(value="/upload.do", method = RequestMethod.POST)
    //上传的文件会转换成MultipartFile对象，file名字对应html中上传控件的name
    @RequestMapping(value = "/uploadEquRecord",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResultDto upload(MultipartFile file) {
        try{
            //取得当前上传文件的文件名称
            String originalFilename = file.getOriginalFilename();
            System.out.println();
            String s = DateUtil.formatDate(new Date());
            //transferTo是保存文件，参数就是要保存到的目录和名字
            file.transferTo(new File(property+"/equRecord/" + s+".xlsx"));
            ExcelUtil.readEquRecordExcel(property+"/equRecord/" + s+".xlsx");
            List<EquRecordData> equRecordDataList = equRecordDataListener.getEquRecordDataList();
            List<EquRecordDto> equRecordDtoList = new ArrayList<>();
            for(EquRecordData recordData: equRecordDataList){
                List<Equipment> equipment = equMessageService.selectOneEqu(recordData.getEquName(), recordData.getEquNum());
                EquRecordDto equRecordDto = new EquRecordDto();
                equRecordDto.setEquModel(equipment.get(0).getEquModel());
                equRecordDto.setEquName(equipment.get(0).getEquName());
                equRecordDto.setContractNo(recordData.getContractNo());
                equRecordDto.setEquNum(equipment.get(0).getEquNum());
                equRecordDto.setEndDate(recordData.getEndDate());
                equRecordDto.setStartDate(recordData.getStartDate());
                equRecordDto.setUserName(recordData.getUserName());
                equRecordDtoList.add(equRecordDto);
            }
            logger.info("文件类型："+file.getContentType());
            logger.info("原文件名："+originalFilename);
            logger.info("文件大小："+file.getSize());
            return new JsonResultDto("上传成功","200",equRecordDtoList);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new JsonResultDto("201","上传失败");
        }
    }
}
